import 'package:extended_text/extended_text.dart';
import 'package:flutter/material.dart';
import 'package:osc/common/MyTextStyle.dart';
import 'package:osc/data/repository/repository.dart';
import 'package:osc/common/osc_user_manager.dart';
import 'package:osc/models/entity/osc_base_list_entity.dart';
import 'package:osc/models/entity/osc_tweet_comment_entity.dart';
import 'package:osc/models/pop_result/pop_result.dart';
import 'package:osc/res/dimens.dart';
import 'package:osc/res/strings.dart';
import 'package:osc/ui/pages/account/login_page.dart';
import 'package:osc/ui/pages/project/project_detail_page.dart';
import 'package:osc/ui/pages/tweet/topic_tweet_page.dart';
import 'package:osc/ui/pages/user/user_profile.dart';
import 'package:osc/ui/widgets/image_loader.dart';
import 'package:osc/ui/widgets/no_data_widget.dart';
import 'package:osc/ui/widgets/small_widgets.dart';
import 'package:osc/ui/widgets/web_scaffold.dart';
import 'package:osc/utils/navigator_util.dart';
import 'package:osc/utils/pd_util.dart';
import 'package:osc/utils/special_text/my_special_text_span_builder.dart';
import 'package:osc/utils/special_text/special_text_bean.dart';
import 'package:osc/utils/string_util.dart';
import 'package:osc/utils/time_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

/// 动弹评论列表
/// isHotComment 是否精彩评论列表
class TweetCommentList extends StatefulWidget {
  final int id;
  final bool isHotComment;
  final bool enableLoadMore;
  final bool shrinkWrap;


  const TweetCommentList({Key key, @required this.id, this.enableLoadMore = true, this.shrinkWrap = false, this.isHotComment = false}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return new TweetCommentListState(id, enableLoadMore, shrinkWrap, isHotComment);
  }
}

class TweetCommentListState extends State<TweetCommentList> with AutomaticKeepAliveClientMixin<TweetCommentList> {
  final int id;
  final bool isHotComment;
  final bool enableLoadMore;
  final bool shrinkWrap;
  TweetCommentListState(this.id, this.enableLoadMore, this.shrinkWrap, this.isHotComment,);

  HttpRepository httpRepository;
  String pageToken;
  int size = 0;
  bool isLoadedData = false;
  int commentOrder = 0;

  double paddingParentHorizontal = Dimens.gap_activity_horizontal;
  double paddingChildVertical = Dimens.gap_view_normal;
  double paddingChildHorizontal = Dimens.gap_view_normal;
  double portraitSize = Dimens.view_item_icon_height_bigger;


  List<OscTweetComment> list;

  RefreshController refreshController;

  @override
  void initState() {
    super.initState();
    if(isHotComment){
      commentOrder = 1;
    }
    refreshController = RefreshController(initialRefresh: true);
    httpRepository = HttpRepository();
  }

  @override
  void dispose() {
    super.dispose();
    refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return SmartRefresher(
      controller: refreshController,
      onRefresh: refresh,
      onLoading: loadMore,
      enablePullUp: enableLoadMore,
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if (size == 0) {
            return NoDataWidget();
          } else {
            return buildListItem(index);
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return SmallWidgets.buildLine();
        },
        itemCount: isLoadedData && size == 0? 1 : size,
        shrinkWrap: shrinkWrap,
      ),
    );
  }

  buildListItem(int index){
    OscTweetComment item = list.elementAt(index);
    return GestureDetector(
      onTap: (){
        print("---ontap");
      },
      child: Container(
        padding: EdgeInsets.only(left: paddingParentHorizontal, right: paddingParentHorizontal, top: paddingParentHorizontal, bottom: paddingParentHorizontal),
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            buildUser(item),
            buildContentText(item.content),
          ],
        ),
      ),
    );
  }

  buildUser(OscTweetComment item){
    return Padding(
      padding: EdgeInsets.only(bottom: paddingChildVertical),
      child: Row(
        children: <Widget>[
          buildPortrait(item.author.portrait),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: paddingChildHorizontal),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  buildText(item.author.name, Colors.black, Dimens.font_sp14),
                  SmallWidgets.buildLine(color: Colors.transparent, height: Dimens.gap_view_smaller),
                  buildText(TimeUtil.timeFormat(item.pubDate), Colors.black54, Dimens.font_sp10),
                ],
              ),
            ),
          ),
          buildLike(0),
        ],
      ),
    );
  }

  buildPortrait(String imageUrl){
    return Container(
      width: portraitSize,
      height: portraitSize,
      child: ClipOval(
        child: ImageLoader(url: imageUrl),
      ),
    );
  }

  buildLike(int like){
    return Padding(
      padding: EdgeInsets.symmetric(vertical: paddingChildVertical),
      child: GestureDetector(
        onTap: (){

        },
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            buildText("$like ", Colors.black54, Dimens.font_sp12),
            Image.asset(PdUtil.getImagePath("ic_thumb_normal"), width: Dimens.view_item_icon_height_smaller, fit: BoxFit.fitWidth,),
          ],
        ),
      ),
    );
  }

  buildContentText(String text){
    return ExtendedText(
      text,
      style: MyTextStyle.TWEET_CONTENT,
      onSpecialTextTap: (dynamic parameter) {
        if(parameter is SpecialTextBean){
          SpecialTextBean bean = parameter;
          switch(bean.type){
            case SpecialTextBean.TYPE_PROJECT:
              jumpToPageForResult(ProjectDetailPage(ident: bean.value,));
              break;
            case SpecialTextBean.TYPE_USER:
              jumpToPageForResult(UserProfile(userId: bean.id, nickName: bean.value,));
              break;
            case SpecialTextBean.TYPE_TOPIC:
              jumpToPageForResult(TopicTweetPage(topicName: bean.value,));
              break;
            case SpecialTextBean.TYPE_URL:
              jumpToPageForResult(WebScaffold(url: bean.value, title: "",));
              break;
          }
        }
      },
      specialTextSpanBuilder: MySpecialTextSpanBuilder(),
      overflow: TextOverflow.ellipsis,
      maxLines: 10,
    );
  }


  buildText(String data, Color color, double fontSize) {
    return SmallWidgets.buildText(data, color, fontSize);
  }

  Future<Null> refresh() async{
    pageToken = null;
    list?.clear();
    return await loadMore();
  }


  Future<Null> loadMore() async{
    isLoadedData = true;
    int requestCount = 0;
    int responseCount = 0;
    await httpRepository.getTweetCommentList(tweetId: id, pageToken: pageToken, order: commentOrder).then((resp){
      if(resp != null && resp.success){
        OscBaseListResult<OscTweetComment> result = resp.result;
        requestCount = result.requestCount;
        responseCount = result.responseCount;
        if(result != null){
          List<OscTweetComment> tempList = result.items;
          if(StringUtil.isEmpty(pageToken)){
            list = tempList;
          } else {
            list.addAll(tempList);
          }
          size = list?.length??0;
          pageToken = result.nextPageToken;
        }
      }
    });
    setState(() {
      if(requestCount > responseCount){
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
      refreshController.refreshCompleted();
    });
  }

  jump2PageForResult(Widget page, {bool checkLogin = false}) {
    if(checkLogin){
      if(OscUserManager.getInstance().isLogin()){
        jumpToPageForResult(page);
      } else {
        jumpToPageForResult(LoginPage());
        showTips(StringIds.userNoLogin);
      }
    } else {
      jumpToPageForResult(page);
    }
  }
  jumpToPageForResult(Widget page) {
    NavigatorUtil.pushPageForResult<PopResult>(context, page).then((result) {
      if (result != null) {
        switch (result.id) {
          case PopResult.ID_LOGIN:
            break;
        }
      }
    });
  }

  showTips(String msg){
    PdUtil.showToast(msg: msg);
  }

  @override
  bool get wantKeepAlive => true;
}
